// components/calendar/index.js
import defaultProps from './props/index'
import { isArray, isDate } from '../../utils/type'
import {
  getPrevDay,
  getNextDay,
  getToday,
  compareDay,
  copyDates,
  calcDateNum,
  formatMonthTitle,
  compareMonth,
  getMonths,
  getDayByOffset,
  requestAnimationFrame,
} from './utils';

const getTime = (date) => isDate(date) ? date.getTime() : date;

Component({
  properties: {
    // 是否显示
    show: {
      type: Boolean,
      observer(val) {
        if (val) {
          this.initRect();
          this.scrollIntoView();
        }
      },
    },
    // 默认选中的日期
    defaultDate: {
      type: null,
      observer(val) {
        this.setData({ currentDate: val });
        this.scrollIntoView();
      },
    },
    ...defaultProps
  },

  data: {
    subtitle: '',
    scrollIntoView: '',
    currentDate: null,
  },

  attached() {
    this.setData({
      currentDate: this.getInitDate(this.data.defaultDate),
    });
  },

  ready() {
    const { show, poppable } = this.data;
    if (show || !poppable) {
      this.initRect();
      this.scrollIntoView();
    }
  },

  methods: {
    onScroll() {
      wx.nextTick(() => {
        const { enableScroll, subtitle, showSubtitle, show } = this.data;
        (enableScroll && show && showSubtitle) && this.triggerEvent('scroll', this._replaceChineseString(subtitle));
      })
    },

    _replaceChineseString(string) {
      return string.replace('年', '-').replace('月', '')
    },

    reset() {
      this.setData({ currentDate: this.getInitDate() });
      this.scrollIntoView();
    },

    // 初始化节点信息
    initRect() {
      if (this.contentObserver != null) {
        this.contentObserver.disconnect();
      }

      const contentObserver = this.createIntersectionObserver({
        thresholds: [0, 0.1, 0.9, 1],
        observeAll: true,
      });

      // 全局享用
      this.contentObserver = contentObserver;

      contentObserver.relativeTo('.body');
      contentObserver.observe('.month', (res) => {
        if (res.boundingClientRect.top <= res.relativeRect.top) {
          this.setData({ subtitle: formatMonthTitle(res.dataset.date) });
        }
      });
    },

    // 限制日期选择范围
    limitDateRange(date, minDate, maxDate) {
      minDate = minDate || this.data.minDate;
      maxDate = maxDate || this.data.maxDate;
      if (compareDay(date, minDate) === -1) {
        return minDate;
      }
      if (compareDay(date, maxDate) === 1) {
        return maxDate;
      }
      return date;
    },

    // 获取初始日期
    getInitDate(defaultDate) {
      const { type, minDate, maxDate, allowSameDay } = this.data;
      const now = getToday().getTime();

      if (type === 'range') {
        if (!isArray(defaultDate)) {
          defaultDate = [];
        }

        const [startDay, endDay] = defaultDate || [];
        const startDate = getTime(startDay || now);
        const start = this.limitDateRange(
          startDate,
          minDate,
          allowSameDay ? startDate : getPrevDay(new Date(maxDate)).getTime()
        );
        const date = getTime(endDay || now);
        const end = this.limitDateRange(
          date,
          allowSameDay ? date : getNextDay(new Date(minDate)).getTime()
        );

        return [start, end];
      }

      if (type === 'multiple') {
        if (isArray(defaultDate)) {
          return defaultDate.map((date) => this.limitDateRange(date));
        }

        return [this.limitDateRange(now)];
      }

      if (!defaultDate || isArray(defaultDate)) {
        defaultDate = now;
      }

      return this.limitDateRange(defaultDate);
    },

    scrollIntoView() {
      requestAnimationFrame(() => {
        const { currentDate, type, show, poppable, minDate, maxDate } =
          this.data;
        const targetDate = type === 'single' ? currentDate : currentDate[0];
        const displayed = show || !poppable;
        if (!targetDate || !displayed) {
          return;
        }

        const months = getMonths(minDate, maxDate);

        months.some((month, index) => {
          if (compareMonth(month, targetDate) === 0) {
            this.setData({ scrollIntoView: `month${index}` });
            return true;
          }

          return false;
        });
      });
    },

    onOpen() {
      this.triggerEvent('open');
    },

    onOpened() {
      this.triggerEvent('opened');
    },

    onClose() {
      console.log('close')
      this.triggerEvent('close');
    },

    onClosed() {
      this.triggerEvent('closed');
    },

    // TODO: 这一块逻辑写的有点冗余，后面再优化
    onClickDay(event) {
      if (this.data.readonly) {
        return;
      }

      let { date } = event.detail;
      const { type, currentDate, allowSameDay } = this.data;

      if (type === 'range') {
        const [startDay, endDay] = currentDate;
        if (startDay && !endDay) {
          const compareToStart = compareDay(date, startDay);
          if (compareToStart === 1) {
            const { days } = this.selectComponent('.month').data;
            days.some((day, index) => {
              const isDisabled =
                day.type === 'disabled' &&
                getTime(startDay) < getTime(day.date) &&
                getTime(day.date) < getTime(date);
              if (isDisabled) {
                ({ date } = days[index - 1]);
              }
              return isDisabled;
            });
            this.select([startDay, date], true);
          } else if (compareToStart === -1) {
            this.select([date, null]);
          } else if (allowSameDay) {
            this.select([date, date], true);
          }
        } else {
          this.select([date, null]);
        }
      } else if (type === 'multiple') {
        let selectedIndex;

        const selected = currentDate.some((dateItem, index) => {
          const equal = compareDay(dateItem, date) === 0;
          if (equal) {
            selectedIndex = index;
          }
          return equal;
        });

        if (selected) {
          const cancelDate = currentDate.splice(selectedIndex, 1);
          this.setData({ currentDate });
          this.unselect(cancelDate);
        } else {
          this.select([...currentDate, date]);
        }
      } else {
        this.select(date, true);
      }
    },

    unselect(dateArray) {
      const date = dateArray[0];
      if (date) {
        this.triggerEvent('unselect', copyDates(date));
      }
    },

    select(date, complete) {
      if (complete && this.data.type === 'range') {
        const valid = this.checkIsLegalRange(date);

        if (!valid) {
          if (this.data.showConfirm) {
            this.emit([
              date[0],
              getDayByOffset(date[0], this.data.maxRange - 1),
            ]);
          } else {
            this.emit(date);
          }
          return;
        }
      }

      this.emit(date);
      if (complete && !this.data.showConfirm) {
        this.onConfirm();
      }
    },

    emit(date) {
      this.setData({
        currentDate: isArray(date) ? date.map(getTime) : getTime(date),
      });
      this.triggerEvent('select', copyDates(date));
    },

    // 检查是否是合法的日期选择范围
    checkIsLegalRange(date) {
      const { maxRange, rangePrompt, showRangePrompt } = this.data;

      if (maxRange && calcDateNum(date) > maxRange) {
        if (showRangePrompt) {
          wx.showToast({
            title: rangePrompt || `选择天数不能超过 ${maxRange} 天`,
            icon: 'none'
          })
        }
        this.triggerEvent('over-range');

        return false;
      }

      return true;
    },

    onConfirm() {
      const { type, currentDate } = this.data;
      if (
        type === 'range' &&
        !this.checkIsLegalRange(currentDate)
      ) {
        return;
      }
      wx.nextTick(() => {
        this.triggerEvent('confirm', copyDates(currentDate));
      });
    },

    onClickSubtitle(event) {
      this.triggerEvent('click-subtitle', event);
    },
  },
})